﻿
namespace SistemaLogistica.Windows.Forms.BienPatrimonial.Operaciones
{
    using System;
    using System.Data.Linq;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.EventArgs;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfVenta : MaestroDetalleSeguro, Observador
    {
        public CwfVenta()
        {
            InitializeComponent(); 
            
            this.dgvDetalle.DataGridView.KeyDown += new KeyEventHandler(DataGridView_KeyDown);
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        private void dtpFechaBusqueda_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                this.MaestroBindingSource.DataSource = VentaManager.Instancia.Buscar(this.dtpFecha.Value);
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void dgvDetalle_BeforeShowControl(object sender, BeforeShowControlEventArg e)
        {
            switch (e.Cell.ColumnIndex)
            {
                case 0: // Cargar Bienes Patrimoniales
                    try
                    {
                        ComboBox cmbBP = e.Control as ComboBox;
                        cmbBP.DataSource = null;
                        cmbBP.DisplayMember = "Bien";
                        cmbBP.ValueMember = "IdBien";
                        cmbBP.DataSource = BienPatrimonialManager.Instancia.Listar();
                    }
                    catch (Exception ex)
                    {
                        Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, ex.Message);
                    }
                    break;
                default:
                    break;
            }
        }

        private void dgvDetalle_EnterKeyPress(object sender, EnterKeyPressEventArg e)
        {
            switch (e.ColumnIndex)
            {
                case 0: // Bien Patrimonial
                    if (!string.IsNullOrEmpty(e.Text))
                    {
                        BienPatrimonial bienPatrimonial = BienPatrimonialManager.Instancia.ObtenerPorNombre(e.Text);
                        if (bienPatrimonial != null)
                        {
                            this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[1].Value = bienPatrimonial.Tipo; 
                            this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[2].Value = bienPatrimonial.StockActual;
                            this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[3].Value = bienPatrimonial.Precio;
                        }
                        else
                        {
                            e.Handle = false;
                        }
                    }
                    else
                    {
                        e.Handle = false;
                    }
                    break;
                case 2: // Cantidad
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else if (Convert.ToDecimal(e.Text) <= 0)
                    {
                        e.Handle = false;
                    }
                    break;
                case 3: // Precio Base
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else if (Convert.ToDecimal(e.Text) <= 0)
                    {
                        e.Handle = false;
                    }
                    if (e.Handle)
                    {
                        if (this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[0].Tag != null)
                        {
                            int count = this.dgvDetalle.DataGridView.Rows.Count;
                            if (this.dgvDetalle.DataGridView.Rows[count - 1].Cells[0].Value != null)
                            {
                                if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea agregar un nuevo Detalle?") == DialogResult.Yes)
                                {
                                    this.dgvDetalle.DataGridView.Rows.Add();
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.dgvDetalle.DataGridView.CurrentCell != null)
                {
                    if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea eliminar el Detalle?") == DialogResult.No)
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        this.dgvDetalle.DataGridView.Rows.Remove(this.dgvDetalle.DataGridView.CurrentRow);
                        if (this.dgvDetalle.DataGridView.Rows.Count == 0)
                        {
                            this.dgvDetalle.DataGridView.Rows.Add();
                        }
                    }
                }
            }
        }

        protected override void InitialLoad()
        {
            try
            {
                LoadClientes();
                this.MaestroBindingSource.DataSource = VentaManager.Instancia.Listar();
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                OcultarColumnas();
                LoadDataGridView();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, ex.Message);
            }
        }

        private void LoadClientes()
        {
            this.cmbCliente.DisplayMember = "Descripcion";
            this.cmbCliente.ValueMember = "IdCliente";
            this.cmbCliente.DisplayColumnNames = "IdCliente,Descripcion,Telefono";
            this.cmbCliente.DataSource = ClienteManager.Instancia.Listar();
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["FechaVenta"].Visible = false;
            this.dgvMaestro.Columns["IdEmpleado"].Visible = false;
            this.dgvMaestro.Columns["IdCliente"].Visible = false;
            this.dgvMaestro.Columns["Serie"].Visible = false;
            this.dgvMaestro.Columns["Numero"].Visible = false;
            this.dgvMaestro.Columns["Cliente"].Visible = false;
            this.dgvMaestro.Columns["Empleados"].Visible = false;
            this.dgvMaestro.Columns["IdVenta"].HeaderText = "Subastas";
        }

        private void LoadDataGridView()
        {
            this.dgvDetalle.DataGridView.Rows.Clear();
            this.dgvDetalle.DataGridView.Columns.Clear();
            this.dgvDetalle.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Bien";
            colummn.HeaderText = "Bien";
            colummn.Width = 150;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Descripcion";
            colummn.HeaderText = "Descripción";
            colummn.ControlType = CustomControlType.TextBox;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Cantidad";
            colummn.HeaderText = "Cantidad";
            colummn.Width = 80;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Precio";
            colummn.HeaderText = "Precio";
            colummn.Width = 100;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            this.dgvDetalle.DataGridView.Rows.Add();
            this.dgvDetalle.DataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            Venta venta = this.MaestroBindingSource[e.RowIndex] as Venta;

            if (venta != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);

                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "ID: " + venta.IdVenta.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "ID: " + venta.IdVenta.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 8);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, "S: " + venta.Serie + "  N°: " + venta.Numero, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
                else
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);
                    if (selected)
                        TextRenderer.DrawText(e.Graphics, venta.FechaVenta.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, venta.FechaVenta.ToShortDateString(), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, venta.Cliente.Descripcion, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
            }
        }

        protected override void EventoNuevo()
        {
            this.dtpFecha.Enabled = false;
            this.dtpFecha.Value = EmpresaManager.Instancia.Fecha();
            this.dtpFecha.Focus();
        }

        protected override void EventoEditar()
        {
            this.dtpFecha.Enabled = true;
            this.dtpFecha.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void LoadData(object obj)
        {
            Venta venta = obj as Venta;
            if (venta != null)
            {
                venta = VentaManager.Instancia.ObtenerPorID(venta.IdVenta);

                this.identificador = venta.IdVenta;
                this.dtpFecha.Value = venta.FechaVenta;
                this.txtSerie.Text = venta.Serie;
                this.txtNumero.Text = venta.Numero;
                this.cmbCliente.SelectedValue = venta.IdCliente;
                this.txtDescripcion.Text = venta.Descripcion;

                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleVenta d in venta.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Descripcion;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantida;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[3].Value = d.Monto;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        VentaManager.Instancia.Registrar(GetVenta());
                        break;
                    case EstadoActual.Editar:
                        VentaManager.Instancia.Modifcar(GetVenta());
                        break;
                    case EstadoActual.Eliminar:
                        VentaManager.Instancia.Eliminar(Convert.ToInt32(this.identificador));
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
            return result;
        }

        private Venta GetVenta()
        {
            Venta venta = new Venta
            {
                IdVenta = Convert.ToInt32(this.identificador),
                IdEmpleado = Empresa.Usuario.IdEmpleado,
                FechaVenta = this.dtpFecha.Value,
                Serie = this.txtSerie.Text,
                Numero = this.txtNumero.Text,
                IdCliente = Convert.ToInt32(this.cmbCliente.SelectedValue),
                Descripcion = this.txtDescripcion.Text
            };
            foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    venta.Detalle.Add(new DetalleVenta
                    {
                        Bien = new Bien { IdBien = Convert.ToInt32(row.Cells[0].Tag) },
                        Descripcion = row.Cells[1].Value.ToString(),
                        Cantida = Convert.ToDecimal(row.Cells[2].Value),
                        Monto = Convert.ToDecimal(row.Cells[3].Value)
                    });
                }
            }
            return venta;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[0].Tag == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[2].Value == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[3].Value == null)
            {
                result = false;
            }
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.txtSerie.Text.Trim().Length != 4)
            {
                this.errValidator.SetError(this.txtSerie, "Ingresar Serie del Documento Correcta.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.txtSerie, string.Empty);
            }
            if (this.txtNumero.Text.Trim().Length != 7)
            {
                this.errValidator.SetError(this.txtNumero, "Ingresar Numero del Documento Correcto.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.txtNumero, string.Empty);
            }
            if (this.cmbCliente.SelectedIndex == -1)
            {
                this.errValidator.SetError(this.cmbCliente, "Seleccionar Cliente.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbCliente, string.Empty);
            }
            if (this.dgvDetalle.DataGridView.Rows.Count == 0)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, "Ingresar los Bienes para la Venta.");
                result = false;
            }
            return result;
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            LoadDataGridView();
            base.ClearControls();
        }

        #region Miembros de Observador

        public void Notificar(object mensaje)
        {
            LoadClientes();
        }

        #endregion
    }
}
